//
//  DownLoadInfoController.m
//  HB
//
//  Created by 陶秋安 on 16/3/24.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "DownLoadInfoController.h"


@implementation DownLoadInfoController

-(void) delClick:(NSIndexPath *)indexPath
{
    DownloadedCell *cell = (DownloadedCell *)[tvLeft cellForRowAtIndexPath:indexPath];
    
    [FxFileUtility deleteFile:cell.localP];
    
    [dictLocal removeObjectForKey:[cell.musicInfo objectForKey:@"MusicID"]];
    
    [self loadLocalFile];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    dictLocal=[[NSMutableDictionary alloc] init];
    
    [leftArray removeAllObjects];
    
    [self loadLocalFile];
    
    [self.view addSubview:self.slideBar];
    
    dlos =[DownLoadObjects sharedMyClass];
    
    [dlos setDelegate:self];
    
    rightArray= dlos.downLoadTask;
    
    [self initScrollView];
    
}


-(void) loadLocalFile
{
    [dictLocal removeAllObjects];
    
    leftArray= [[NSMutableArray alloc]init];
    
    NSFileManager* fm = [NSFileManager defaultManager];
    
    NSString *path = [NSString stringWithFormat:@"%@/%@", [FxGlobal getRootPath], DownLoadPath];
    
    NSArray *subFiles = [fm subpathsAtPath:path];
    
    for (NSString* fileName in subFiles)
    {
        if ([fileName hasSuffix:@"mp3"])
        {
            
            NSString *fname = [fileName substringToIndex:36];
            
            if(![dictLocal.allKeys containsObject:fname])
            {
            
                [dictLocal setObject:[NSString stringWithFormat:@"%@/%@",path,fileName] forKey:fname];
            
                [self loadMusic:fname];
                
            }
        }
    }
}

-(void) loadMusic : (NSString *) musicID
{
    
    operation= [[NetWorkOperation alloc] initWithDelegate:self];
    
    NSString *url= [FxGlobal getServiceUrl:@"Music" andFuncName:@"MusicByID"];
    
    NSDictionary *dictInfo = @{@"url": [NSString stringWithFormat:@"%@?musicID=%@",url,musicID] };
    
    [operation setOpInfo:dictInfo];
    
    [operation get:0];
    
}

-(void) opSuccessForGet:(id)data andFlag:(NSInteger)flag
{
    operation= nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *data2 = [dataStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
    
    if ([[data2 objectForKey:@"result"] isEqualToString:@"1"])
    {
        NSArray *arrayData= [data2 objectForKey:@"data"];
        
        for (NSInteger i=0; i<arrayData.count; i++)
        {
            
            NSDictionary *dict= [arrayData objectAtIndex:i];
            
            [leftArray addObject:dict];
        }
    }
    
    [tvLeft performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}

-(void)del
{
    
    rightArray= dlos.downLoadTask;
    
    [tvRight performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
    
    [self loadLocalFile];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)setNavigationLeft:(NSString *)imageName sel:(SEL)sel
{
    
}

- (void)setNavigationRight:(NSString *)imageName sel:(SEL)sel
{
    
}

- (void)setNavigationTitleImage:(NSString *)imageName
{
    self.navigationItem.title = @"我的下载";
}

-(void) setSlidePostion
{
    
    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:_slideBar attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
    
    [self.view addConstraint:leftConstraint];
    
    NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:_slideBar attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f];
    
    [self.view addConstraint:rightConstraint];
    
    
    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:_slideBar attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTopMargin multiplier:1.0f constant:66.0f];
    
    [self.view addConstraint:topConstraint];
}

-(CXSlideBar *)slideBar
{
    if (!_slideBar)
    {
        NSArray *array = [NSArray arrayWithObjects:@"已下载",@"下载中",nil];
        
        _slideBar = [CXSlideBar initWithFrame:CGRectMake(0, 66, DeviceWidth, 40) Array:array];
        
        _slideBar.delegate = self;
    }
    
    return  _slideBar;
}

-(void) initScrollView
{
    svContent=[[UIScrollView alloc]init];
    
    svContent.pagingEnabled=YES;
    
    svContent.delegate=self;
    
    svContent.backgroundColor=[UIColor lightGrayColor];
    
    svContent.translatesAutoresizingMaskIntoConstraints=NO;
    
    [self.view addSubview:svContent];
    
    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:svContent attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
    
    [self.view addConstraint:leftConstraint];
    
    NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:svContent attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f];
    
    [self.view addConstraint:rightConstraint];
    
    
    NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:svContent attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0f constant:106.0f];
    
    [self.view addConstraint:topConstraint];
    
    NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:svContent attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottomMargin multiplier:1.0f constant:0.0f];
    
    [self.view addConstraint:bottomConstraint];
    
    [self addView];
    
}

-(void) addView
{
    for (NSInteger i=0; i<2; i++)
    {
        UIView *view =[[UIView alloc] init];
        
        view.translatesAutoresizingMaskIntoConstraints= NO;
        
        [svContent addSubview:view];
        
        if(i==0)
        {
            view.backgroundColor=[UIColor grayColor];
            
            //ImageView左侧与父视图左侧对齐
            NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:svContent attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
            
            [svContent addConstraint:leftConstraint];
        }
        //ImageView顶部与父视图顶部对齐
        NSLayoutConstraint *topConstraint1 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:svContent attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
        
        //ImageView底部与父视图顶部对齐
        NSLayoutConstraint *bottomConstraint1 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:svContent attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f];
        
        //ImageView高度为父视图高度
        NSLayoutConstraint* heightConstraint1 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:svContent attribute:NSLayoutAttributeHeight multiplier:1.0f constant:0.0f];
        
        //ImageView宽度为父视图宽度
        NSLayoutConstraint* widthConstraint1 = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:svContent attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f];
        
        //iOS 6.0或者7.0调用addConstraints
        [svContent addConstraints:@[bottomConstraint1, topConstraint1,heightConstraint1,widthConstraint1]];
        
        
        //imageView 右边距和父视图对齐 以便确定父视图的内容边界
        if(i>0)
        {
            UIView *view1=(UIView * ) svContent.subviews[i-1];
            
            NSLayoutConstraint *spaceConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:view1 attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:0.0f];
            
            [svContent addConstraint:spaceConstraint];
            
        }
        if(i==0)
            [self addTableViewLeft:view];
        else
            [self addTableViewRight:view];
        
    }
    
    UIView *view1=(UIView * )svContent.subviews[1];
    
    NSLayoutConstraint *Constraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:svContent attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:0.0f];
    
    [svContent addConstraints:@[ Constraint ]];
}

-(void) addTableViewLeft :(UIView *)view
{
    tvLeft=[[UITableView alloc] init];
    
    tvLeft.delegate=self;
    
    tvLeft.dataSource=self;
    
    tvLeft.translatesAutoresizingMaskIntoConstraints=NO;
    
    [view addSubview:tvLeft];
    
    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:tvLeft attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:view
                                                                      attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
    
    [view addConstraint:leftConstraint];
    
    NSLayoutConstraint *topConstraint1 = [NSLayoutConstraint constraintWithItem:tvLeft attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
    
    [view addConstraint:topConstraint1];
    
    NSLayoutConstraint *bottomConstraint1 = [NSLayoutConstraint constraintWithItem:tvLeft attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f];
    
    [view addConstraint:bottomConstraint1];
    
    
    NSLayoutConstraint *rightConstraint1 = [NSLayoutConstraint constraintWithItem:tvLeft attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f];
    
    [view addConstraint:rightConstraint1];
    
}

-(void) addTableViewRight :(UIView *)view
{
    tvRight=[[UITableView alloc] init];
    
    tvRight.delegate=self;
    
    tvRight.dataSource=self;
    
    tvRight.translatesAutoresizingMaskIntoConstraints=NO;
    
    [view addSubview:tvRight];
    
    NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:tvRight attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:view
                                                                      attribute:NSLayoutAttributeLeading multiplier:1.0f constant:0.0f];
    
    [view addConstraint:leftConstraint];
    
    NSLayoutConstraint *topConstraint1 = [NSLayoutConstraint constraintWithItem:tvRight attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
    
    [view addConstraint:topConstraint1];
    
    NSLayoutConstraint *bottomConstraint1 = [NSLayoutConstraint constraintWithItem:tvRight attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f];
    
    [view addConstraint:bottomConstraint1];
    
    
    NSLayoutConstraint *rightConstraint1 = [NSLayoutConstraint constraintWithItem:tvRight attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f];
    
    [view addConstraint:rightConstraint1];
    
}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat x1= ((UIView *)scrollView.subviews[0]) .frame.origin.x;
    
    CGFloat x2= ((UIView *)scrollView.subviews[1]).frame.origin.x;
    
    CGFloat x= scrollView.contentOffset.x;
    
    if(x==x1)
    {
        
        [_slideBar moveTo:0];
        
    }
    else if(x==x2)
    {
        
        [_slideBar moveTo:1];
    }
    
}

-(void)slideBarTouch:(CXSlideBar *)slideBar atIndex:(NSInteger)index
{
    if(index==0)
    {
        CGPoint point = CGPointMake(0, 0);
        
        svContent.contentOffset = point;
    }
    else
    {
        CGPoint point = CGPointMake(DeviceWidth, 0);
        
        svContent.contentOffset = point;
    }
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([tableView isEqual:tvRight])
    {
        return rightArray.count;
    }
    else
    {
        return leftArray.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if([tableView isEqual:tvLeft])
    {
        static NSString * const cellIdentifier = @"DownloadedCell";
        
        DownloadedCell *cell = (DownloadedCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (cell == nil) {
            
            NSArray* Objects = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:tableView options:nil];
            
            cell = [Objects objectAtIndex:0];
            
        }
        
        cell._delegate= self;
        
        cell.row = indexPath;
        
        cell.selectionStyle= UITableViewCellSelectionStyleNone;
        
        NSDictionary *music=[leftArray objectAtIndex:indexPath.row];
        
        cell.musicInfo= music;
        
        cell.lblMusicName.text= [music objectForKey:@"MusicName"];
        
        cell.localP = [dictLocal objectForKey:[music objectForKey:@"MusicID"]];
        
        return cell;
    }
    else
    {
        
        NSString  *cellIdentifier = @"DownloadingCell";
        
        DownloadingCell *cell = (DownloadingCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (cell == nil) {
            
            NSArray* Objects = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:tableView options:nil];
            
            cell = [Objects objectAtIndex:0];
            
        }
        
        cell.selectionStyle= UITableViewCellSelectionStyleNone;
        
        DownLoad *dict=[rightArray objectAtIndex:indexPath.row];
        
        [dict setDel:cell];
        
        cell.lblMusicName.text= dict->zyMusic.name;
        
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([tableView isEqual:tvLeft])
    {
        [ZYMusicTool playingMusic].playing=NO;
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        DownloadedCell *cell = (DownloadedCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        //获取新的歌曲
        [ZYMusicTool playingMusic].playing=NO;
        
        //获取新的歌曲
        ZYMusic *currMusic=[[ZYMusic alloc]init];
        
        currMusic.name= [cell.musicInfo objectForKey:@"MusicName"];
        
        currMusic.icon= [cell.musicInfo objectForKey:@"Icon"];
        
        currMusic.iconName= [cell.musicInfo objectForKey:@"IconName"];
        
        currMusic.musicListArray=[cell.musicInfo objectForKey:@"musiclist"];
        
        currMusic.lrcname=@"";
        
        currMusic.singer=[cell.musicInfo objectForKey:@"singer"];
        
        currMusic.djID=[cell.musicInfo objectForKey:@"ID"];
        
        currMusic.singerIcon=[cell.musicInfo objectForKey:@"singericon"];
        
        currMusic.musicID =[cell.musicInfo objectForKey:@"MusicID"];
        
        currMusic.playing = YES;
        
        currMusic.shareURL=[cell.musicInfo objectForKey:@"shareURL"];
        
        [ZYMusicTool setPlayingMusic:currMusic];
        
        [self musicPlay].playMode=@"one";
        
        [self.view.window.rootViewController presentViewController:[self musicPlay] animated:true completion:nil];
        
    }
}

@end
